package com.yxt.qmgf.home.ctrl;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yxt.qmgf.common.ClientSession;
import com.yxt.qmgf.home.GGVO;
import com.yxt.qmgf.home.dao.gonggaoDao;

import com.yxt.qmgf.userinfo.vo.UserInfoVO;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.Callback;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;

public class AboutPageController {

    @FXML
    private TextField searchField;
    @FXML
    private TableView<GGVO> announcementTable;
    @FXML
    private Button addButton;

    private UserInfoVO userInfo;
    private gonggaoDao gonggaoDao = SpringUtil.getBean(gonggaoDao.class);
    private ObservableList<GGVO> announcementList = FXCollections.observableArrayList();

    public void initialize() {
        userInfo = (UserInfoVO) ClientSession.getAttribute("user_info");
        if (userInfo != null) {
            if (userInfo.getCode().equals("1")) {
                addButton.setVisible(true);
            }
        }

        // 从数据库查询数据并赋值给 announcementList
        List<GGVO> ggvos = gonggaoDao.selectList(null);
        for (GGVO ggvo : ggvos) {
            GGVO newGGVO = new GGVO();
            newGGVO.setTitle(ggvo.getTitle());
            newGGVO.setContent(ggvo.getContent());
            newGGVO.setCreate_time(ggvo.getCreate_time());
            newGGVO.setCreator(ggvo.getCreator());
            announcementList.add(newGGVO);
        }

        // 初始化表格列
        announcementTable.setItems(announcementList);
        announcementTable.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("title"));
        announcementTable.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("content"));
        announcementTable.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("create_time"));
        announcementTable.getColumns().get(3).setCellValueFactory(new PropertyValueFactory<>("creator"));

        // 设置操作列的单元格工厂
        TableColumn<GGVO, Void> actionColumn = (TableColumn<GGVO, Void>) announcementTable.getColumns().get(4);
        actionColumn.setCellFactory(new ActionCellFactory());

        // 不需要再调用 loadAnnouncements("");，因为数据已经在上面赋值完成
        // loadAnnouncements("");
    }

    @FXML
    private void searchAnnouncements() {
        String searchText = searchField.getText();
        loadAnnouncements(searchText);
    }

    private void loadAnnouncements(String searchText) {
        announcementList.clear();
        QueryWrapper<GGVO> queryWrapper = new QueryWrapper<>();
        if (!searchText.isEmpty()) {
            queryWrapper.like("title", searchText);
        }
        List<GGVO> announcements = gonggaoDao.selectList(queryWrapper);
        announcementList.addAll(announcements);
    }

    @FXML
    private void showAddDialog() {
        // 实现新增公告的逻辑，例如打开一个新的对话框
        Dialog<GGVO> dialog = new Dialog<>();
        dialog.setTitle("新增公告");
        dialog.setHeaderText("请填写公告信息");

        ButtonType saveButtonType = new ButtonType("保存", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(saveButtonType, ButtonType.CANCEL);

        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20, 150, 10, 10));

        TextField titleField = new TextField();
        titleField.setPromptText("标题");
        TextArea contentArea = new TextArea();
        contentArea.setPromptText("内容");

        grid.add(new Label("标题:"), 0, 0);
        grid.add(titleField, 1, 0);
        grid.add(new Label("内容:"), 0, 1);
        grid.add(contentArea, 1, 1);

        dialog.getDialogPane().setContent(grid);

        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == saveButtonType) {
                GGVO ggVO = new GGVO();
                ggVO.setTitle(titleField.getText());
                ggVO.setContent(contentArea.getText());
                // 获取当前日期和时间
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                ggVO.setCreate_time(LocalDateTime.now().format(formatter));
                ggVO.setCreator(userInfo.getName());
                // 不手动设置 ID 值
                return ggVO;
            }
            return null;
        });

        Optional<GGVO> result = dialog.showAndWait();
        result.ifPresent(ggVO -> {
            gonggaoDao.insert(ggVO);
            loadAnnouncements("");
        });
    }

    public class ActionCellFactory implements Callback<TableColumn<GGVO, Void>, TableCell<GGVO, Void>> {
        @Override
        public TableCell<GGVO, Void> call(TableColumn<GGVO, Void> param) {
            return new TableCell<>() {
                private final Button editButton = new Button("编辑");
                private final Button deleteButton = new Button("删除");
                private final Button viewButton = new Button("查看");

                {
                    editButton.setOnMouseClicked((MouseEvent event) -> {
                        GGVO ggVO = getTableView().getItems().get(getIndex());
                        // 实现编辑逻辑
                        showEditDialog(ggVO);
                    });
                    deleteButton.setOnMouseClicked((MouseEvent event) -> {
                        GGVO ggVO = getTableView().getItems().get(getIndex());
                        // 实现删除逻辑
                        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                        alert.setTitle("确认删除");
                        alert.setHeaderText(null);
                        alert.setContentText("确定要删除这条公告吗？");
                        Optional<ButtonType> result = alert.showAndWait();
                        if (result.isPresent() && result.get() == ButtonType.OK) {
                            // 使用注入的 gonggaoDao 实例进行删除操作
                            gonggaoDao.del(ggVO.getId());
                            loadAnnouncements("");
                        }
                    });
                    viewButton.setOnMouseClicked((MouseEvent event) -> {
                        GGVO ggVO = getTableView().getItems().get(getIndex());
                        // 实现查看逻辑
                        showViewDialog(ggVO);
                    });

                    if (userInfo != null && userInfo.getCode().equals("1")) {
                        setGraphic(new HBox(5, editButton, deleteButton, viewButton));
                    } else {
                        setGraphic(new HBox(5, viewButton));
                    }
                }

                @Override
                protected void updateItem(Void item, boolean empty) {
                    super.updateItem(item, empty);
                    if (empty) {
                        setGraphic(null);
                    } else {
                        if (userInfo != null && userInfo.getCode().equals("1")) {
                            setGraphic(new HBox(5, editButton, deleteButton, viewButton));
                        } else {
                            setGraphic(new HBox(5, viewButton));
                        }
                    }
                }
            };
        }
    }

    private void showEditDialog(GGVO ggVO) {
        // 实现编辑公告的逻辑，例如打开一个新的对话框
        Dialog<GGVO> dialog = new Dialog<>();
        dialog.setTitle("编辑公告");
        dialog.setHeaderText("请修改公告信息");

        ButtonType saveButtonType = new ButtonType("保存", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(saveButtonType, ButtonType.CANCEL);

        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20, 150, 10, 10));

        TextField titleField = new TextField(ggVO.getTitle());
        TextArea contentArea = new TextArea(ggVO.getContent());

        grid.add(new Label("标题:"), 0, 0);
        grid.add(titleField, 1, 0);
        grid.add(new Label("内容:"), 0, 1);
        grid.add(contentArea, 1, 1);

        dialog.getDialogPane().setContent(grid);

        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == saveButtonType) {
                ggVO.setTitle(titleField.getText());
                ggVO.setContent(contentArea.getText());
                // 保留原有的创建时间
                ggVO.setCreate_time(ggVO.getCreate_time());
                return ggVO;
            }
            return null;
        });

        Optional<GGVO> result = dialog.showAndWait();
        result.ifPresent(updatedVO -> {
            // 使用注入的 gonggaoDao 实例进行更新操作
            gonggaoDao.Update(updatedVO);
            loadAnnouncements("");
        });
    }

    private void showViewDialog(GGVO ggVO) {
        // 实现查看公告的逻辑，例如打开一个新的对话框
        Dialog<Void> dialog = new Dialog<>();
        dialog.setTitle("公告详情");
        dialog.setHeaderText(null);

        ButtonType okButtonType = new ButtonType("确定", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().add(okButtonType);

        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20, 150, 10, 10));

        Label titleLabel = new Label("标题: " + ggVO.getTitle());
        Label contentLabel = new Label("内容: " + ggVO.getContent());
        Label createTimeLabel = new Label("创建时间: " + ggVO.getCreate_time());
        Label creatorLabel = new Label("创建人: " + ggVO.getCreator());

        grid.add(titleLabel, 0, 0);
        grid.add(contentLabel, 0, 1);
        grid.add(createTimeLabel, 0, 2);
        grid.add(creatorLabel, 0, 3);

        dialog.getDialogPane().setContent(grid);

        dialog.showAndWait();
    }

    // 设置 gonggaoDao 的 setter 方法，用于注入
    public void setGonggaoDao(gonggaoDao gonggaoDao) {
        this.gonggaoDao = gonggaoDao;
    }
}